// domain.js
// Implement domain redirection.

var DomainStatus = {};
var DomainReadyCallback = null;
var domainRegEx = /^([^:]+:\/\/)([^\/]+)/;
function onBeforeRequest(details)
{
	var domain = details.url.match(domainRegEx)[2];
	if(KnownDomains.indexOf(domain) != -1 && 
		domain != Options.Domain.Current)
		return {redirectUrl:details.url.replace(domainRegEx, "$1" + 
			Options.Domain.Current)};
}

function onTabsUpdated(tabId, changeInfo, tab)
{
	var domain_match = (changeInfo.url || "").match(domainRegEx);
	var domain;
	if(domain_match && (domain = domain_match[2]) && 
		KnownDomains.indexOf(domain) != -1 && 
		domain != Options.Domain.Current)
		chrome.tabs.update(tabId, {url: changeInfo.url.replace(
			domainRegEx, "$1" + Options.Domain.Current)});
}

function CheckDomain(domain, callback)
{
	var url = "http://" + domain + "/thread.php?fid=1";
	XHR.SendRequest(url, (function(xhr)
	{
		DomainStatus[domain] = "ok";
		callback(DomainStatus);
	}), (function(xhr)
	{
		if(xhr.status == 404)
			DomainStatus[domain] = "unavailable";
		else
			DomainStatus[domain] = "error";
		callback(DomainStatus);
	}), {fullUrl: true});
}

Options.Domain.onChanged = (function(details)
{
	if(Options.Domain.Force)
	{
		chrome.webRequest && chrome.webRequest.onBeforeRequest.addListener(
			onBeforeRequest, {urls: DomainMatchPatterns}, ["blocking"]);
		!chrome.webRequest && chrome.tabs.onUpdated.addListener(
			onTabsUpdated);
	}
	else
	{
		chrome.webRequest && chrome.webRequest.onBeforeRequest.
			removeListener(onBeforeRequest);
		!chrome.webRequest && chrome.tabs.onUpdated.removeListener(
			onTabsUpdated);
	}
});

if(Options.Domain.Preference == "autoDetect")
{
	CheckDomain("bbs.stuhome.net", function(status)
	{
		if(status["bbs.stuhome.net"] == "unavailable" && DomainsInfo[Options.Domain.Current] == "internal")
			Options.Domain.Current = Options.Domain.PreferredExternalDomain;
		else if(status["bbs.stuhome.net"] == "ok" && DomainsInfo[Options.Domain.Current] == "external" && 
			Options.Domain.Preference == "default")
			Options.Domain.Current = Options.Domain.PreferredInternalDomain;
		DomainReadyCallback && DomainReadyCallback();
	});
}
else
	DomainReadyCallback && DomainReadyCallback();

Options.Domain.Force && Options.Domain.onChanged(
	{name: "Force", newValue: true});

